#!/bin/bash

configfile="../conf/config/sshservers.conf"
ECHO="echo -e"

let i=0
print_display() {
    while read line
    do
        let i=i+1
        $ECHO "\t $i   $line"
    done < $configfile
}

if [ ! -f $configfile ]; then
    $ECHO "$configfile doesn't exist."
    exit
fi

$ECHO "\n"
print_display
$ECHO "\n"

read -p "    Which one do you want to connect to: " indx

if [ "$indx" == "q" ]; then
    $ECHO "Quit"
    exit 0
fi

if [ "$indx" == "n" ]; then
    read -p "===== remote address: " cip
    read -p "===== remote port: " cport
    read -p "===== username: " cuser
    read -p "===== password: " cpd
    if [ -z "$cip" -o -z "$cuser" ]; then
         $ECHO "Must give all of ip , user, passwd"
         exit
    fi
    echo "$cip $cport $cuser $cpd" >> $configfile
else

let i=0
while read line
do
    let i=i+1
    if [ $i = $indx ]; then
        cip=`echo $line | cut -d' ' -f 1`
        cport=`echo $line | cut -d' ' -f 2`
        cuser=`echo $line | cut -d' ' -f 3`
        cpd=`echo $line | cut -d' ' -f 4`
        $ECHO "$cip $cport $user"
        break
    fi
done < $configfile

fi

auto_login_ssh () {
expect -c "set timeout 5;
spawn ssh -p $1 -o StrictHostKeyChecking=no $3 ${@:4} $5;
expect assword:;
send -- $2\r;
interact;";
}

echo "Will connect to $cuser@$cip with $cpd"
auto_login_ssh $cport $cpd $cuser@$cip
